<template>
  <Header></Header>
  <div class="fixed">

    <div class="bgColor">
      <h1 class="main-shopcart">购物车</h1>
    </div>

    <div class="container">

      <div class="main">
        <div class="nav">
          <span class="left">全部书籍</span>
        </div>
        <ul class="head">
          <li class="item check">
            <el-checkbox 
              v-model="isCheckAll" 
              @change="checkAllFn"
            >全选</el-checkbox>
          </li>
          <li class="item classInfo">书籍信息</li>
          <li class="item price">单价(元)</li>
          <li class="item count">数量(本)</li>
          <li class="item total">总价(元)</li>
          <li class="item stock">库存(本)</li>
          <li class="item function">操作</li>
        </ul>
        <!-- 有订单 -->
        <div v-if="cartList.length != 0">
          <!-- 循环出每一个购物车数据 -->
          <ul 
            class="haveorder" 
            v-for="(item) in cartList" 
            :key="item.bookId"
          >
            <li class="order-item">
              <el-checkbox v-model="item.checked"></el-checkbox>
            </li>
            <li class="order-item info">
              <div class="courseimg">
                <img :src="item.bookInfo.photo" alt="" />
              </div>
              <div class="course-name">{{ item.bookInfo.book_name }}</div>
            </li>

            <li class="order-item">￥{{ item.bookInfo.price }}</li>
            <li class="order-item num">
              <el-input-number 
                v-model="item.count" 
                :min="1" 
                :max="item.bookInfo.stock"
                :size="small"
                @change="numberChange(item)" 
              />
            </li>
            <li class="order-item totoalprice">￥{{ item.total_price }}</li>
            <li class="order-item stock">{{ item.bookInfo.stock1 }}</li>
            <li class="order-item delete">
              <div>
                <i class="el-icon-delete"></i>
                <el-popconfirm 
                  title="确定将该项移出您的购物车吗?"
                  @confirm="deleteBook(item)"
                >
                  <template #reference>
                    <el-button 
                      type="danger" 
                      plain 
                      class="deletd-text"
                    >
                      删除
                    </el-button>
                  </template>
                </el-popconfirm>
              </div>
            </li>
          </ul>
        </div>
        <!-- 没有订单 -->
        <div class="noOrder" v-else>
          <div class="order-alert">哎呦！暂无订单</div>
        </div>
        <el-divider class="line"></el-divider>
        <!-- footer -->
        <ul class="foot">
          <li class="foot-item">
            已选书籍
            <span class="unique">
              {{ selectList.length }}
            </span>
          </li>
          <li class="foot-item">
            合计
            <span class="unique">
              {{ totalPrice.toFixed(2) }}
            </span>
          </li>
          <li>
            <button class="btn" @click="goToOrder">去结算</button>
          </li>
        </ul>
      </div>

    </div>
  </div>


  <Footer :bgColor="'gray'"></Footer>
  
</template>

<script setup>
//components
import Header from "@/components/common/Header.vue";
import Footer from '@/components/common/Footer.vue'
import { onBeforeMount, onMounted, reactive, watch, watchEffect } from "vue";

// router
import { useRouter } from "vue-router";
// store
import { useStore } from 'vuex'
// api
import cartModelApi from '@/request/api/cart.js'

const router = useRouter();
const store = useStore();

// 初始化购物车列表
const cartList = reactive([]);

const getInitCartData = () => {
  // 获取当前购物车列表并存入vuex
  store.dispatch('getCartList', store.state.user.userInfo.username);
  // cartModelApi.getCartListApi({
  //   user_name: store.state.user.userInfo.username
  // }).then(res => {
  //   // 请求获取购物车接口并存入
  //   // console.log('res.data', res.data)
  //   store.commit("setCartList", res.data);
  // })
}

onBeforeMount(() => {
  getInitCartData();
})

watchEffect(() => {
  setTimeout(() => {
    cartList.push(...store.state.cart.cartList.filter(item => item['order_status'] != 2));
    cartList.forEach(item => {
      item.checked = true;
      item.bookInfo.stock1 = item.bookInfo.stock - item.count;
      item.un_price = +item.bookInfo.price;
      item.total_price = (item.count * item.un_price).toFixed(2);
    })
    getTotalPrice();
  }, 300);
})

// 计算选择的书籍列表数据
const selectList = computed(() => {
  return cartList.filter(item => item.checked);
})
const totalPrice = ref(0);

// 防抖定时器
let timer = null;

// 修改数量 ==> 算出item对应的总价和库存
const numberChange = item => {
  item.total_price = (item.count * item.un_price).toFixed(2);
  item.bookInfo.stock1 = item.bookInfo.stock - item.count;
  getTotalPrice();

  // 防抖
  // clearTimeout(timer);
  // timer = setTimeout(() => {

  // }, 2000)
  
}


// 计算选中书籍的总价
function getTotalPrice(){
  totalPrice.value = 0;
  console.log('selectList.value', selectList.value)
  selectList.value.forEach(item => {
    totalPrice.value += +item.total_price;
  })
}

// 全选状态
const isCheckAll = ref(true);

// 监听
watch(selectList, (newVal, oldVal) => {
  getTotalPrice();
  // isCheckAll.value = cartList.length === selectList.value.length;
})

// 点击全选时的回调
const checkAllFn = () => {
  if(isCheckAll.value){
    // 全选
    cartList.forEach(item => {
      item.checked = true;
    })
  }else{
    // 全不选
    cartList.forEach(item => {
      item.checked = false;
    })
  }
}

// 确定删除
const deleteBook = (item) => {
  // console.log('item', item)
  cartModelApi.deleteCartApi({
    order_id: item.order_id
  }).then(res => {
    ElMessage({
      showClose: true,
      type: 'success',
      message: res.msg,
    })
    // 重新获取
    const loadingInstance = ElLoading.service({ fullscreen: true, text: '亲,数据加载中,请稍等...' });
    
    setTimeout(() => {
      getInitCartData();
      router.go(0);
      loadingInstance.close()
    },600)
  })
} 

// 点击去结算
const goToOrder = () => {
    
  selectList.value.forEach(item => {
    let p = {
      count: item.count,
      order_id: item.order_id,
      bookId: item.bookId,
      order_status: 1,
      un_price: item.un_price
    };
    cartModelApi.updateCartApi(p);
  })
  store.commit('setSelList', selectList.value);
  router.push('/order');
}

</script>

<style scoped lang="less">
.fixed {
  background: #ffffff;
}
.bgColor {
  width: 100%;
  height: 200px;
  background-color: red;
  background: linear-gradient(-45deg, #ee7752, #e73c7e, #23a6d5, #23d5ab);
  background-size: 400% 400%;
  animation: gradient 15s ease infinite;
}
@keyframes gradient {
  0% {
    background-position: 0% 50%;
  }
  50% {
    background-position: 100% 50%;
  }
  100% {
    background-position: 0% 50%;
  }
}
.container {
  width: 1200px;
  margin: -100px auto 50px auto;
  background: #ebedf2;
  border-radius: 12px;
  box-shadow: 0px 2px 5px #888888;
}
.main {
  padding: 20px;
  border-radius: 5px;
}
.main-shop {
  position: relative;
  display: flex;
  align-content: center;
}
.main-shop i {
  font-size: 35px;
  padding: 20px 10px 0 0;
  color: #ff4400;
  font-weight: bold;
}
.main-shopcart {
  width: 1200px;
  margin: 0 auto;
  height: 42px;
  font-size: 24px;
  font-family: Microsoft YaHei;
  font-weight: bold;
  line-height: 35px;
  color: #ffffff;
  padding: 30px 0;
  opacity: 1;
}
.nav {
  display: flex;
  justify-content: space-between;
  border-bottom: 2px solid #e6e6e6;
}
.nav .left {
  width: 80px;
  height: 26px;
  font-size: 18px;
  font-family: Microsoft YaHei;
  font-weight: bold;
  line-height: 0px;
  color: #ff4400;
  opacity: 1;
  border-bottom: 2px solid #ff4400;
}
.nav .right {
  width: 108px;
  height: 24px;
  font-size: 14px;
  font-family: Microsoft YaHei;
  font-weight: 400;
  line-height: 0px;
  color: #333333;
  opacity: 0.5;
}

/* 头部开始 */
.head {
  display: flex;
  padding: 0 10px;
  margin: 20px 0;
  width: 100%;
  height: 35px;
  line-height: 35px;
  background: #fcfcfc;
  opacity: 1;
  border-radius: 0px;
  box-sizing: border-box;
  border-radius: 5px;
  box-shadow: 0px 2px 5px 2px #cccccc;
}
.head .item {
  width: 150px;
  font-size: 14px;
  color: #333333;
}
.check .all {
  margin-right: 10px;
}
.check .text {
  width: 1487px;
  height: 40px;
}
.classInfo {
  width: 400px !important;
  color: #333333;
}
/* 头部结束 */

/* 订单开始 */
.haveorder {
  display: flex;
  width: 100%;
  height: 250px;
  background: #fcfcfc;
  margin-bottom: 10px;
  border-radius: 5px;
  box-shadow: 0px 2px 5px 2px #cccccc;
}
.haveorder .order-item {
  height: 250px;
  line-height: 200px;
  margin: 5px;
}
.order-item:first-child {
  width: 30px;
}
.order-item {
  width: 150px;
  font-size: 16px;
  color: #333333;
}
.totoalprice {
  color: #e2231a;
}
.num {
  width: 150px !important;
  .el-input-number{
    width: 120px;
  }
}
.info {
  display: flex;
  width: 410px !important;
  height: 250px;
  line-height: 200px;
}
.courseimg {
  margin: 40px 20px 40px 0;
  width: 150px;
  height: 170px;
}
.courseimg img {
  width: 100%;
  height: 100%;
}
.info .course-name {
  width: 300px;
  word-break: keep-all;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.delete {
  cursor: pointer;
}
.deletd-text {
  margin-left: 5px;
}

/* 订单结束 */

/* 暂无订单开始 */
.noOrder {
  width: 100%;
  height: 100%;
  text-align: center;
  margin: 200px 0;
}
.order-alert {
  height: 31px;
  font-size: 20px;
  font-family: Microsoft YaHei;
  font-weight: 400;
  line-height: 0px;
  color: #b5b9bc;
  opacity: 1;
  margin: 20px 120px;
}
/* 暂无订单结束 */
.foot {
  display: flex;
  justify-content: flex-end;
  width: 100%;
  height: 40px;
  line-height: 40px;
  color: #333333;
  margin-bottom: 10px;
}
.foot-item {
  width: 120px;
  height: 40px;
  line-height: 40px;
  font-size: 14px;
  font-weight: 400;
  color: #333333;
}
.unique {
  margin-left: 5px;
  font-size: 24px;
  color: #ff4400;
}
.btn {
  width: 120px;
  height: 40px;
  margin-left: 20px;
  border: none;
  color: #ffffff;
  font-size: 22px;
  border-radius: 5px;
  background: #ff4400;
  cursor: pointer;
  box-shadow: 0px 3px 5px 2px #ff727f;
}

</style>
